import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Form, Input, Button, InputNumber, message, Image } from 'antd'
import { getProduct, updateProduct, uploadProductImg } from '@/api/product'
import { typeProduct, updateProductParams } from '@/types/product'
import './index.scss'

const ProductManage = () => {
  const { productId } = useParams<{productId:string}>()
  const [product, setProduct] = useState<typeProduct>()

  useEffect(() => {
    loadProduct()
  }, [])

  const loadProduct = async() => {
    const res = await getProduct(productId)

    setProduct(res.data)
    console.log(res.data)
  }

  /**
   * 更新产品
   */
  const onclickUpdate = async(e:updateProductParams) => {
    if (!product) {
      return
    }
    try {
      await updateProduct(productId, {
        ...e,
        image: product.image
      })
      message.success('更新成功')
      loadProduct()
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * 选择图片后回调：上传图片
   */
  const selectFile = async(e:any) => {
    if (product && e.target.files.length > 0) {
      try {
        const formData:FormData = new FormData()

        formData.append('image', e.target.files[ 0 ])
        const res = await uploadProductImg(formData)

        setProduct({
          ...product,
          image: res.data
        })
        message.success('图片已上传')
        console.log(res.data)
      } catch (err) {
        console.log(err)
      }
    }
    e.target.value = ''
  }

  return product
    ? (
      <div className="product-edit">
        <h2>编辑商品信息</h2>
        <Form
          autoComplete="off"
          className="edit-form"
          initialValues={product}
          labelAlign="left"
          labelCol={{ span: 6 }}
          onFinish={onclickUpdate}
        >
          <Form.Item
            className="cover"
            label="封面图"
          >
            <label title="替换封面">
              <Image
                preview={false}
                src={product.image}
                style={{ cursor: 'pointer' }}
                width={200}
              />
              <input
                accept="image/**"
                className="select-file"
                onChange={selectFile}
                type="file"
              />
            </label>
          </Form.Item>
          <Form.Item
            label="商品名"
            name="name"
            rules={[{ required: true, message: '请输入商品名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="类别"
            name="category"
            rules={[{ required: true, message: '请输入类别' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="品牌"
            name="brand"
            rules={[{ required: true, message: '请输入品牌' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="库存"
            name="countInStock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item
            label="描述信息"
            name="description"
            rules={[{ required: true, message: '请输入邮编' }]}
          >
            <Input.TextArea autoSize={{ minRows: 4, maxRows: 10 }} />
          </Form.Item>
          <Form.Item>
            <Button
              className="submit-btn"
              htmlType="submit"
              type="primary"
            >
            修改产品信息
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
    : null
}

export default ProductManage
